package com.ad.aidai.activitys.order_score;

import android.content.Context;

import com.ad.aidai.bean.Comment;
import com.ad.aidai.bean.Order;
import com.ad.aidai.bean.User;
import com.ad.aidai.common.ADApp;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.events.CommonEvent;
import com.ad.aidai.network.ADUrl;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.NetResult;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * StatePresenter
 * <p>
 * Created by Yusxon on 17/2/6.
 */

public class OrderScorePresenter implements OrderScoreContract.Presenter {

    private Context mContext;
    private OrderScoreContract.View mView;
    private CompositeSubscription mSubscriptions;

    private Order order;

    private int scorer = 0;

    public OrderScorePresenter(Context context, OrderScoreContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
        order = ADApp.getOrder();
    }

    @Override
    public void subscribe() {
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
        mSubscriptions.clear();
        mSubscriptions = null;
    }

    @Override
    public void loadUser() {
        User user = order.getSendUser();

        String url = ADUrl.HEAD_ICON_URL.replace("{schoolId}", user.getSchoolId() + "").replace("{photoName}", user
                .getUserIcon());
        mView.showUserHead(url);
        mView.showUserName(user.getUserName());
        mView.showUserSex(user.getUserSex());
    }

    @Override
    public void loadOrder() {
        mView.showOrderContent(order.getOrderContent());
    }

    private int commentShow = 3;
    private int sumScore = 0;

    @Override
    public void submit() {
        long commentReceiverId = order.getOrderReceiveId();
        long commentSenderId = order.getOrderSendId();

        if (ADApp.getUser().getUserId().equals(commentSenderId)) {
            scorer = 0;
        } else if (ADApp.getUser().getUserId().equals(commentReceiverId)) {
            scorer = 1;
        }

        long orderId = order.getOrderId();
        int[] scores = mView.getScore();
        for (int score : scores) {
            if (score == 0) {
                mView.toast("请确定所有选项已评分");
                return;
            }
            sumScore += score;
        }
        sumScore /= 3;
        if (order.getSendUser().getUserId().equals(ADApp.getUser().getUserId())) {
            commentShow = 2;
        }

        Map<String, String> maps = new HashMap<>();
        maps.put("commentReceiverId", String.valueOf(commentReceiverId));
        maps.put("commentSenderId", String.valueOf(commentSenderId));
        maps.put("orderId", String.valueOf(orderId));
        maps.put("commentScore", String.valueOf(sumScore));
        maps.put("commentShow", String.valueOf(commentShow));

        mView.showLoading();
        NetWork.getOrderOperationApi()
                .mutualComment(maps)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetResult>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("OrderScorePresenter").e(e.getMessage());
                        mView.closeLoading(false);
                    }

                    @Override
                    public void onNext(NetResult result) {
                        if (result.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            mView.closeLoading(true);
                            ADApp.getOrder().setOrderStatus(commentShow);
                            //如果我是发单人
                            if (ADApp.getUser().getUserId().equals(ADApp.getOrder().getSendUser().getUserId())) {
                                ADApp.getOrder().setSenderComment(new Comment(0, ADApp.getOrder().getOrderSendId(),
                                        ADApp.getOrder().getOrderReceiveId(), sumScore, "", ADApp.getOrder()
                                        .getOrderId(), commentShow));
                            } else {
                                ADApp.getOrder().setReceiverComment(new Comment(0, ADApp.getOrder().getOrderReceiveId(),
                                        ADApp.getOrder().getOrderSendId(), sumScore, "", ADApp.getOrder()
                                        .getOrderId(), commentShow));
                            }
                            RxBus.getInstance().postEvent(new CommonEvent<>(CommonEvent.ORDER_STATUS_CHANGE, ADApp
                                    .getOrder()));
                            mView.exit();
                        } else {
                            if (result.getCode() == StatusCodeFromNet.CODE_HAD_SCORE) {
                                mView.toast("已经评分过了,每个单只能评分一次");
                                mView.exit();
                            }
                            Logger.t("OrderScorePresenter").e(result.toString());
                            mView.closeLoading(false);
                        }
                    }
                });

    }

    @Override
    public int getScorer() {
        return scorer;
    }
}
